<template>
  <div>
    <div class="flex_wrap_between_middle tab-price">
      <ul class="monthly-nav">
        <li class="monthly-nav-item">
          <el-dropdown placement="bottom-start" @command="checkItem">
            <el-button type="primary" class="monthly-nav-item-check-btn">
              {{ activeName }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu class="el-menu-box">
                <el-dropdown-item
                  v-for="(item, index) in financialOptions"
                  :key="index"
                  :command="item.code"
                  >{{ item.name }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </li>
        <li class="monthly-nav-item">
          <el-radio-group v-model="tabPosition" @change="changeRadio">
            <el-radio-button label="price">金额</el-radio-button>
            <el-radio-button label="useNumber">数量</el-radio-button>
          </el-radio-group>
        </li>
      </ul>
      <div class="date-list">
        <a
          v-for="(item, index) of dateList"
          :key="index"
          :class="dateValue === item.value ? 'slip-edit' : ''"
          @click.stop="clickDate(item.value)"
        >
          <p>{{ item.label }}</p>
        </a>
      </div>
    </div>

    <div class="layui-row">
      <div v-if="permission" class="layui-col-md12">
        <div id="monthlyConsume" style="height: 300px"></div>
      </div>
      <div v-else class="noPermiss">
        <NoPermiss :title="title"></NoPermiss>
      </div>
    </div>
  </div>
</template>

<script setup name="monthlyConsumeBar">
import * as echarts from 'echarts'
import NoPermiss from '@/components/NoPermiss/index'
import { getConsumeBar, getDepotConsumeBar } from '@/api/workbench'

const { proxy } = getCurrentInstance()
const props = defineProps({
  permissionPrice: {
    type: Boolean,
    default: true,
  },
  permissionList: {
    type: Boolean,
    default: true,
  },
})
const activeIndex = ref('')
const activeName = ref('全部')
const tabPosition = ref('price')
const title = ref('金额')
const permission = computed(() => {
  return props.permissionList
})
const dateList = reactive([
  { label: '一周', value: 'week' },
  { label: '一个月', value: 'month' },
  { label: '三个月', value: 'months' },
  { label: '半年', value: 'year' },
])
const options = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999',
      },
    },
  },
  color: ['#3db2ee'],
  xAxis: {
    // name: '日期（日）',
    type: 'category',
  },
  yAxis: {
    name: '使用金额（元）',
    type: 'value',
  },
  series: [
    {
      name: '使用金额',
      type: 'bar',
      barWidth: '40%',
      smooth: true,
    },
  ],
})
const dateValue = ref('week')

const financialOptions = computed(() => {
  let options = proxy.$store.state.permission.dict['financial_account'] || []
  let index = options.findIndex((item) => item.code === 'all')
  if (index === -1) {
    options.unshift({ name: '全部', code: 'all' })
  }
  return options
})
onMounted(() => {
  if (props.permissionPrice) {
    getConsumeBarData()
  }
})
const clickDate = (value) => {
  dateValue.value = value
  changeRadio(tabPosition.value)
}
const getConsumeBarData = () => {
  let params = {
    code: dateValue.value,
    type: activeIndex.value === 'all' ? '' : activeIndex.value,
  }
  getConsumeBar(params).then((res) => {
    if (res) {
      options.xAxis.data = res.data.xAxisData
      options.series[0].data = res.data.seriesData
      options.yAxis.name = '使用金额（元）'
      let dom = document.getElementById('monthlyConsume')
      dom.removeAttribute("_echarts_instance_")
      let echart = echarts.getInstanceByDom(dom)
      console.log('month',echart)
      if (echart === undefined || !echart) {
        echart = echarts.init(dom)
      }
      echart.setOption(options)
      echart.on('click', function (params) {
        proxy.$router.push({
          name: 'consumeOrder',
          params: {
            fromType: 'usage',
            code: dateValue.value,
            type: activeIndex.value,
            date: params.name,
          },
        })
      })
      window.addEventListener('resize', () => {
        echart.resize()
      })
    }
  })
}
const getDepotConsumeBarData = () => {
  let params = {
    code: dateValue.value,
    type: activeIndex.value === 'all' ? '' : activeIndex.value,
  }
  getDepotConsumeBar(params).then((res) => {
    if (res) {
      options.xAxis.data = res.data.xAxisData
      options.series[0].data = res.data.seriesData
      options.yAxis.name = '使用量'
      let dom = document.getElementById('monthlyConsume')
      let echart = echarts.getInstanceByDom(dom)
      if (echart === undefined || !echart) {
        echart = echarts.init(dom)
      }
      echart.setOption(options)
      echart.on('click', function (params) {
        proxy.$router.push({
          name: 'consumeOrder',
          params: {
            fromType: 'usage',
            code: dateValue.value,
            type: activeIndex.value,
            date: params.name,
          },
        })
      })
      window.addEventListener('resize', () => {
        echart.resize()
      })
    }
  })
}
const changeRadio = (val) => {
  if (val === 'price') {
    options.series[0].name = '使用金额'
    options.yAxis.name = '使用金额（元）'
    permission.value = props.permissionPrice
    title.value = '金额'
    if (props.permissionPrice) {
      getConsumeBarData()
    }
  } else if (val === 'useNumber') {
    options.series[0].name = '使用数量'
    options.yAxis.name = '使用量'
    title.value = '数量'
    permission.value = props.permissionList
    if (props.permissionList) {
      getDepotConsumeBarData()
    }
  }
}
const checkItem = (str) => {
  activeIndex.value = str
  let obj = financialOptions.value.find((item) => item.code === str)
  activeName.value = obj.name
  changeRadio(tabPosition.value)
}
</script>

<style scoped lang="scss">
.el-menu-box {
  max-height: 500px;
  overflow: hidden;
  overflow-y: auto;
}
.noPermiss {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.tab-price .date-list {
  display: flex;
  font-size: 12px;
}
.tab-price .date-list p {
  padding: 3px 5px;
  cursor: pointer;
}
.monthly-nav {
  display: flex;
  align-items: center;
  .monthly-nav-item {
    padding-right: 12px;
    .el-icon-arrow-down {
      font-size: 14px;
    }
    .monthly-nav-item-check-btn {
      //background-color: #6dc1a9;
      color: #ffffff;
    }
  }
}
</style>
